﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using Moonwish.Core;
using Moonwish.Core.EntityCore;
using Moonwish.Foundation.DataEntity;

namespace Moonwish.Foundation.ValueObjects
{
    /// <summary>
    /// 值对象集合，by zhlin 2011-08-12
    /// </summary>
    public class ValueObjectCollection : NotificationObjectCollection<ValueObject>
    {
        private readonly ValueObjectClass _valueObjectClass;
        private ValueObjectModel _model;

        internal ValueObjectCollection(ValueObjectClass valueObjectClass)
        {
            _valueObjectClass = valueObjectClass;
            _model = valueObjectClass.Model;
        }

        public ValueObjectModel Model
        {
            get
            {
                return _model;
            }
            set
            {
                Debug.Assert(value != null);

                if (_model != value)
                {
                    _model = value;

                    foreach (var item in this)
                    {
                        item.Model = _model;
                    }
                }
            }
        }

        protected override string GetKeyForItem(ValueObject item)
        {
            return item.Id;
        }

        public override void Add(ValueObject item)
        {
            if (item.DataStatus != DataStatus.New || item.Entity.ChangeTracker.State != ObjectState.Added)
            {
                throw new InvalidOperationException(string.Format("值对象“{0}”不是新增状态，无法添加。", item.Name));
            }
            Model.ValueObjectProxy.AddValueObjectCompleted += AddValueObjectCompleted;
            Model.ValueObjectProxy.AddValueObjectAsync(new ObservableCollection<V_FDT_ValueObject> { item.Entity }, "Default", item);
        }

        void AddValueObjectCompleted(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null) return;

                var item = (ValueObject)e.UserState;

                // 加入到业务数据
                base.BaseAdd(item);

                item.Model = Model;

                // 加入到实体集合
                _valueObjectClass.Entity.V_FDT_ValueObjects.Add(item.Entity);

                item.AcceptChanges();
            }
            finally
            {
                Model.ValueObjectProxy.AddValueObjectCompleted -= AddValueObjectCompleted;

                InvokeAddCompleted(this, e);
            }
        }

        /// <summary>
        /// 用于Model查询时使用，不通知(NotifyChanged)。
        /// </summary>
        /// <param name="item"></param>
        internal new void BaseAdd(ValueObject item)
        {
            BaseAdd(item, false);
        }

        public override void Remove(ValueObject item)
        {
            if (item.DataStatus != DataStatus.New)
            {
                throw new InvalidOperationException(string.Format("值对象“{0}”不是新增状态，无法删除。", item.Name));
            }

            Model.ValueObjectProxy.DeleteValueObjectCompleted += DeleteValueObjectCompleted;
            Model.ValueObjectProxy.DeleteValueObjectAsync(new ObservableCollection<string> { item.Id }, "Default", item);
        }

        void DeleteValueObjectCompleted(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null) return;

                if (e.UserState is ValueObject)
                {
                    var item = (ValueObject)e.UserState;

                    // 从业务数据集合中删除
                    BaseRemove(item);

                    // 从缓存实体数据中删除
                    _valueObjectClass.Entity.V_FDT_ValueObjects.Remove(item.Entity);
                }
                else if (e.UserState is IEnumerable<ValueObject>)
                {
                    var items = (IEnumerable<ValueObject>)e.UserState;
                    foreach (var item in items)
                    {
                        if (Contains(item.Id))
                        {
                            // 从业务数据集合中删除
                            BaseRemove(this[item.Id]);

                            // 从缓存实体数据中删除
                            _valueObjectClass.Entity.V_FDT_ValueObjects.Remove(this[item.Id].Entity);
                        }
                    }
                }

                AcceptChanges();
            }
            finally
            {
                Model.ValueObjectProxy.DeleteValueObjectCompleted -= DeleteValueObjectCompleted;

                InvokeRemoveCompleted(this, e);
            }
        }

        public override void Remove(IEnumerable<ValueObject> items)
        {
            var ids = new ObservableCollection<string>();
            foreach (var item in items)
            {
                if (item.DataStatus != DataStatus.New)
                {
                    throw new InvalidOperationException(string.Format("值对象“{0}”不是新增状态，无法删除。", item.Name));
                }
                ids.Add(item.Id);
            }
            if (ids.Count > 0)
            {
                Model.ValueObjectProxy.DeleteValueObjectCompleted += DeleteValueObjectCompleted;
                Model.ValueObjectProxy.DeleteValueObjectAsync(ids, "Default", items);
            }
        }

        public override void Remove(string key)
        {
            Remove(this[key]);
        }

        public override void AcceptChanges()
        {
            foreach (var item in this)
            {
                item.AcceptChanges();
            }
        }
    }
}
